package com.syc.sqlsession;

import com.syc.entity.Configuration;
import com.syc.entity.MappedStatement;
import com.syc.entity.SqlCommandType;

import java.lang.reflect.*;
import java.util.List;

/**
 * @author Shen Yu Chen
 * @create 2020-04-24
 **/
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception{
        return update(statementId,params);
    }

    @Override
    public int delete(String statementId, Object... params) throws Exception{
        return update(statementId,params);
    }

    @Override
    public int update(String statementId, Object... params) throws Exception{
        //通过执行器执行查询语句
        Executor executor = new SimpleExecutor();
        //根据statementId取得MappedStatementMap对应的mappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        return executor.update(configuration,mappedStatement,params);
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        //通过执行器执行查询语句
        Executor executor = new SimpleExecutor();
        //根据statementId取得MappedStatementMap对应的mappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<E> list = executor.query(configuration, mappedStatement, params);
        return list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        //调用findList,返回一条
        List<T> list = selectList(statementId, params);
        if (list != null && list.size() == 1) {
            return list.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(),
                new Class[]{mapperClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        // 底层都还是去执行JDBC代码 //根据不同情况，来调用selctList或者selectOne
                        // 准备参数 1：statmentid :sql语句的唯一标识：namespace.id= 接口全限定名.方法名
                        // 方法名：findAll
                        //获取方法名 findAll
                        String methodName = method.getName();
                        //类名和namespace保持一致
                        String className = method.getDeclaringClass().getName();
                        String statementId = className + "." + methodName;

                        //获取mappedStatement
                        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                        if(mappedStatement == null || mappedStatement.getSqlCommandType() == null){
                            throw new RuntimeException("SQL不存在,请检查");
                        }
                        //判断sql执行类型
                        if(mappedStatement.getSqlCommandType() == SqlCommandType.INSERT
                                || mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE
                                ||mappedStatement.getSqlCommandType() == SqlCommandType.DELETE){
                            return update(statementId,args);
                        }else if(mappedStatement.getSqlCommandType() == SqlCommandType.SELECT){
                            // 准备参数2：params:args
                            // 获取被调用方法的返回值类型
                            Class<?> returnType = method.getReturnType();
                            Type genericReturnType = method.getGenericReturnType();

                            //判断是否进行了泛型类型参数化,从而得到是执行selectList还是执行selectOne
                            if (genericReturnType instanceof ParameterizedType) {
                                List<Object> objects = selectList(statementId, args);
                                return objects;
                            }
                            return selectOne(statementId, args);
                        }else{
                            throw new RuntimeException("错误的SQL类型,请检查");
                        }
                    }
                });

        return (T) proxyInstance;
    }

}
